package lp.polimi.treefinder;

import org.w3c.dom.Document;
import org.w3c.dom.NodeList;


import android.app.ActionBar;
import android.app.ActionBar.Tab;
import android.app.Activity;
import android.app.Fragment;
import android.app.FragmentTransaction;

/** This is different from the standard TabListener: it displays a different fragment according to if
 * the tag list is empty or not.
 */
public class MyTagsTabListener implements ActionBar.TabListener {

	private final Activity mActivity;
	private final String mTag;
	private final String mTagEmpty;

	public MyTagsTabListener(Activity activity, String tag, String tagEmpty) {
		mActivity = activity;
		mTag = tag;
		mTagEmpty = tagEmpty;
	}

	@Override
	public void onTabSelected(Tab tab, FragmentTransaction ft) { 

		ft.setCustomAnimations(
                R.animator.card_flip_right_in, R.animator.card_flip_right_out);
		
		updateTab(ft, false);
	}

	private void updateTab(FragmentTransaction ft, boolean tabIsReselected) {
		
		try {
			Document doc = XMLHandler.getDomElement(mActivity, "leaves.xml");
			NodeList nl = doc.getElementsByTagName(XMLHandler.KEY_LEAF);
			
			if (tabIsReselected) {
				Fragment f = mActivity.getFragmentManager().findFragmentByTag(mTag);
				Fragment fEmpty = mActivity.getFragmentManager().findFragmentByTag(mTagEmpty);
				if (f!=null)
					ft.detach(f);
				if (fEmpty!=null)
					ft.detach(fEmpty);
			}
			
			if (nl.getLength()!=0) {
				if (mActivity.getFragmentManager().findFragmentByTag(mTag)==null)
					instanciateMyTagsFragment(ft);
				else
					ft.attach(mActivity.getFragmentManager().findFragmentByTag(mTag));

			} else {
				if (mActivity.getFragmentManager().findFragmentByTag(mTagEmpty)==null)
					instanciateMyTagsEmptyFragment(ft);
				else 
					ft.attach(mActivity.getFragmentManager().findFragmentByTag(mTagEmpty));

			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	private void instanciateMyTagsFragment (FragmentTransaction ft) {
		ft.add(android.R.id.content, Fragment.instantiate(mActivity, MyTagsFragment.class.getName()), mTag);
	}
	private void instanciateMyTagsEmptyFragment (FragmentTransaction ft) {
		ft.add(android.R.id.content, Fragment.instantiate(mActivity, MyTagsEmptyFragment.class.getName()), mTagEmpty);
	}

	@Override
	public void onTabUnselected(Tab tab, FragmentTransaction ft) {
		
		ft.setCustomAnimations(
                R.animator.card_flip_right_in, R.animator.card_flip_right_out);
		
		Fragment f = mActivity.getFragmentManager().findFragmentByTag(mTag);
		if (f != null) {
			ft.detach(f);
		}
		Fragment f_empty = mActivity.getFragmentManager().findFragmentByTag(mTagEmpty);
		if (f_empty != null)
			ft.detach(f_empty);
	}

	@Override
	public void onTabReselected(Tab tab, FragmentTransaction ft) {
		updateTab(ft, true);
	}
}